package com.bytetool.agent.transformer;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bytetool.agent.util.StringUtils;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

public class ByteToolTransformer implements ClassFileTransformer {

    private String[] includes = new String[]{};

    private String[] excludes = new String[]{};

    private PerformanceTransformer performanceTransformer;

    public ByteToolTransformer(String agentConfig) {
        init(agentConfig);
        this.performanceTransformer = new PerformanceTransformer(includes, excludes);
    }


    /**
     * {includes:"com.app.c,com.app.b",exluces:"aaa,bbb,ccc",url:"http:ssssddd"}
     *
     * @param config
     */
    private void init(String config) {
        JSONObject jsonObject = (JSONObject) JSON.parse(config);
        String excludesConfig = (String) jsonObject.getOrDefault("excludes", "");
        String includesConfig = (String) jsonObject.getOrDefault("includes", "");
        if (!StringUtils.isNullOrEmpty(excludesConfig)) {
            this.excludes = excludesConfig.split(",");
        }
        if (!StringUtils.isNullOrEmpty(includesConfig)) {
            this.includes = includesConfig.split(",");
        }
    }


    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
                            ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        return this.performanceTransformer.transform(loader, className, classBeingRedefined, protectionDomain, classfileBuffer);
    }


}
